﻿//using System;
//using System.Collections.Generic;
//using System.Data.Entity;
//using System.Data.Entity.Infrastructure;
//using System.Linq;
//using System.Web.Security;
//using KPIS.GERP.Models;
//using KPIS.GERP.Models.Class;
//using KPIS.GERP.Models.SYS;
//using KPIS.GERP.Models.SYS.ViewModel;
//using WebMatrix.WebData;

//namespace KPIS.GERP.WEB.GIMS.Class.MemberShip
//{
//    /// <summary>
//    /// This is for WebSecurityX Initial
//    /// It's mean need to connect database directly, do wait to change to web service or wcf service when you have time
//    /// </summary>
//    public class SimpleMembershipInitializer
//    {
//        public IEnumerable<User> _gerpUsers { get; set; }
//        public IEnumerable<UserProfile> _WebSecurityXUserProfiles { get; set; }
//        public readonly SimpleRoleProvider _roleProvider = (SimpleRoleProvider) Roles.Provider;
//        public readonly SimpleMembershipProvider _membership = (SimpleMembershipProvider) Membership.Provider;

//        // This role is hard code, may be change to re-use current user_role of gerp when you have time
//        public readonly string[] _gimsRoles = new[]
//            {
//                "Admin", "Employee", "PurchaseDep", "InventoryDep"
//            };

//        // Wake up all service, and add startup debuging
//        public SimpleMembershipInitializer()
//        {
//            if (WebSecurityX.Initialized || GimsMembership.IsGimsMembershipInitializing) return;

//            GimsMembership.IsGimsMembershipInitializing = true;
//            var startTime2 = DateTime.Now;
//            GimsUtilities.InitialStartLog.Start();
//            DateTime startTime = GimsUtilities.InitialStartLog.InitialDateTimeStart;

//            if(GimsConfigReader.WakeupServiceOnPoolStart)
//            {
//                GimsUtilities.DevMessageTestAdd("Starting services EssWakeUpService from Gims.Web ");
//                new EssWakeUpService.WakeUpServiceClient().WakeUpAsync();
//                GimsUtilities.DevMessageTestAdd("Starting services GbmsWakeUpService from Gims.Web ");
//                new GbmsWakeUpService.GbmsWakeUpServiceClient().WakeUpAsync();
//                GimsUtilities.DevMessageTestAdd("Starting services GhrmsWakeUpService from Gims.Web ");
//                new GhrmsWakeUpService.GhrmsWakeUpServiceClient().WakeUpAsync();
//                GimsUtilities.DevMessageTestAdd("Starting services GfmsWakeUpService from Gims.Web ");
//                new GfmsWakeUpService.GfmsWakeupServiceClient().WakeUpAsync();
//                GimsUtilities.DevMessageTestAdd("Starting services GimsWakeUpService from Gims.Web ");
//                new GimsWakeUpService.GimsWakeUpServiceClient().WakeUpAsync();
//                GimsUtilities.DevMessageTestAdd("Starting services SysWakeUpService from Gims.Web ");
//                new SysWakeUpService.SysWakeUpServiceClient().WakeUpAsync();
//                GimsUtilities.DevMessageTestAdd("Starting WebSecurityX ");
//            }

//            WebSecurityXInitial();

//            GimsMembership.IsGimsMembershipInitializing = false;

//            GimsUtilities.InitialStartLog.InitialDateTimeEnd = DateTime.Now;
//            string endDateTime = GimsUtilities.InitialStartLog.InitialDateTimeEnd.Value.ToString("dd/MM/yyyy HH:mm:ss");
//            string timeTake = StringFormat.TimeSpan(GimsUtilities.InitialStartLog.InitialDateTimeEnd.Value.Subtract(startTime2));
//            GimsUtilities.DevMessageTestAdd(string.Format("#Completed wake up services on {0}, use {1}<hr/>", endDateTime, timeTake));

//        }

//        #region Utility
        
//        // This is initailizing database of WebSecurityX class
//        public void WebSecurityXInitial()
//        {
//            using (var context = new GERPContext())
//            {
//                string databaseConnectionString = context.Database.Connection.ConnectionString;
//                Database.SetInitializer<GERPContext>(null);

//                if (!context.Database.Exists()) // if error occured, most causes will from [database server not start] or [connection string is incorrected]
//                {
//                    ((IObjectContextAdapter) context).ObjectContext.CreateDatabase();
//                }

//                WebSecurityX.InitializeDatabaseConnection("GERPContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);
//            }
//        }
        
//        // Sync between SysScUsers users : WebSecurityX Membership users
//        public void RemoveUserProfileIfNotExistInGerpUser()
//        {
//            foreach (UserProfile u in _WebSecurityXUserProfiles.Where(u => _gerpUsers.FirstOrDefault(o => o.Code == u.UserName) == null))
//            {
//                _membership.DeleteAccount(u.UserName);
//                _membership.DeleteUser(u.UserName, true);
//            }
//        }
        
//        // Sync between SysScUsers users : WebSecurityX Membership users
//        public void UpdateUserIfNotUseWebSecurityXPassword(string userName)
//        {
//            // Found user
//            if ((_membership.GetUser(userName, false)) != null)
//            {
//                // but not valid password
//                if(!WebSecurityX.Login(userName, GimsMembership.WebSecurityXPassword))
//                {
//                    _membership.DeleteAccount(userName);
//                    _membership.DeleteUser(userName, true);
//                    _membership.CreateUserAndAccount(userName, GimsMembership.WebSecurityXPassword);
//                }
//            }
//        }
        
//        // Sync between SysScUsers users : WebSecurityX Membership users
//        public void CreateRoleIfNotExist()
//        {
//            foreach (var roleName in _gimsRoles.Where(roleName => !_roleProvider.RoleExists(roleName)))
//            {
//                _roleProvider.CreateRole(roleName);
//            }
//        }
        
//        // Sync between SysScUsers users : WebSecurityX Membership users
//        public void ClearRole()
//        {
//            var roles = _roleProvider.GetAllRoles();
//            foreach (var role in roles)
//            {
//                var userInRole = _roleProvider.GetUsersInRole(role);
//                foreach (var uir in userInRole)
//                {
//                    try
//                    {
//                        _roleProvider.RemoveUsersFromRoles(new[]
//                            {
//                                uir
//                            }, new[]
//                                {
//                                    role
//                                });
//                    }
//                    catch
//                    {
//                    }
//                }
//            }
//        }
        
//        // Sync between SysScUsers users : WebSecurityX Membership users
//        public void CreateUserIfNotExist(string userName)
//        {
//            if (_membership.GetUser(userName, false) == null)
//            {
//                _membership.CreateUserAndAccount(userName, GimsMembership.WebSecurityXPassword);
//            }
//        }
        
//        // Sync between SysScUsers users : WebSecurityX Membership users
//        public void AddUserToRole(string userName, string roleName)
//        {
//            try
//            {
//                if (!_roleProvider.GetRolesForUser(userName).Any(r => CompareUtility.IsStringsEqual(r, roleName)))
//                    _roleProvider.AddUsersToRoles(new[]
//                        {
//                            userName
//                        }, new[]
//                            {
//                                roleName
//                            });
//            }
//            catch
//            {
//            }
//        }
        
//        // Sync between SysScUsers users : WebSecurityX Membership users
//        public IEnumerable<User> LoadGerpUsers()
//        {
//             return _gerpUsers = new UserService.UserServiceClient().GetUsers().Where(o => o.RecordStatus != RecordStatus.DeletedStatus).ToList();
//        }
        
//        // Sync between SysScUsers users : WebSecurityX Membership users
//        public bool CheckGerpAuthenValidUserPassword(string userName, string password)
//        {
//            if(_gerpUsers == null || !_gerpUsers.Any())
//            {
//                LoadGerpUsers();
//            }
            
//            if(_gerpUsers == null || !_gerpUsers.Any())
//            {
//                return false;
//            } 
//            return _gerpUsers.FirstOrDefault(o=>CompareUtility.IsStringsEqual(o.Code, userName) && o.Password == password) != null;
//        }
//        #endregion
//    }
//}